<template>
  <scroll class="search-list" :pull-up="true" @pullup="pullUpLoad" ref="scroll">
    <ul class="content">
      <li class="item"
      v-for="(song,index) in songs"
      :key="index"
      @click.stop = "emitSong(index,song)">
      <i class="icon-music"></i>
      <h1>{{ song.name}} - {{ song.singer }}</h1>
      </li>
      <div class="loading-wrapper" v-show="startpull" ref="loading">
        <loading></loading>
      </div>
    </ul>
  </scroll>
</template>

<script>
    import Scroll from "@/base/scroll/Scroll";
    import Loading from "@/base/loading/Loading";
    import {mapGetters} from 'vuex'
    import {search} from "@/common/js/song";

    const PER_PAGE = 20
    export default {
        name: "SearchList",
        components: {Scroll,Loading},
        computed: {
            ...mapGetters('search',['query']),
            arryLen(){
              return this.startpull ? (this.count) * PER_PAGE : PER_PAGE
            }
        },
        data(){
            return {
                songs: [],
                page: 1,
                count: 1,
                startpull: false
            }
        },
        methods: {
            async _getSearch(){
                if(!this.query)   return
                let ret = []
                ret = await search(this.query,this.page,1,PER_PAGE)
                if(!ret){
                    this.startpull = false
                    return
                }
                this.songs = this.songs.concat(ret)
                if (this.songs.length < this.arryLen)
                    this.page++
                else {
                    this.startpull = false
                    this.$refs.scroll.finishPullUp()
                }
            },
            emitSong(index,song){
              this.$emit('changehistory',this.songs[index].name)
              this.$emit('select',{
                  index,
                  song,
                  list: this.songs
              })
            },
            pullUpLoad(){
                this.count++
                this.startpull = true
            }
        },
        watch: {
            page(){
                this._getSearch()
            },
            query(){
                this.songs = []
                this._getSearch()
            },
            arryLen() {
                this.page++
            }
        }
    }
</script>

<style scoped lang="stylus">
@import "~common/stylus/variable"
  .search-list
    height 100%
    overflow hidden
    box-sizing border-box
    padding 10px
    .content
      color $color-text-l
      .item
        display flex
        padding 10px 0
        .icon-music
          margin-right 10px
        h1
          overflow hidden
          text-overflow ellipsis
          white-space nowrap


</style>
